package com.alien.admin.modules.utils;

import com.alibaba.fastjson.JSON;
import com.alien.admin.modules.deploy.domain.ServiceDeployParam;
import com.alien.admin.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2014-2021, 厦门神州鹰软件科技有限公司
 * FileName: YamlCicdInfo
 *
 * @author: zengzf
 * Date:     2021/10/8 10:56
 * Description:
 * History:
 */
@Slf4j
public class YamlCicdTool {

    /**
     * 获得yml文件路径
     *
     * @param env
     * @return
     */
    public static String getYmlFileByEnv(String env) {
        return String.format("/param/%s/cicd_%s.yml", env, env);
    }

    /**
     * 获取deployParam的json文件路径
     *
     * @param env
     * @return
     */
    public static String getDeployParamFileByEnv(String env) {
        return String.format("/param/%s/deployParam_%s.json", env, env);
    }

    /**
     * 把配置文件转化为java对象。
     *
     * @return
     */
    public static CicdInfoRoot getCicdInfoRoot(String env) {
        Representer representer = new Representer();
        representer.getPropertyUtils().setSkipMissingProperties(true);
        Yaml yaml = new Yaml(new Constructor(CicdInfoRoot.class), representer);
        String filePath = getYmlFileByEnv(env);
        InputStream inputStream = YamlCicdTool.class.getResourceAsStream(filePath);
        CicdInfoRoot cicdInfoRoot = yaml.load(inputStream);
        return cicdInfoRoot;
    }

    /**
     * 获取deployParam的通用默认值。
     * 默认值值来自一个json文件。
     *
     * @return
     * @throws IOException
     */
    public static ServiceDeployParam getDeploymentParamDefaultCommonValue(String env) throws IOException {
        String filePath = getDeployParamFileByEnv(env);
        InputStream inputStream = YamlCicdTool.class.getResourceAsStream(filePath);
        StringBuffer stringBuffer = new StringBuffer();
        String tmpStr = "";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            while ((tmpStr = reader.readLine()) != null) {
                stringBuffer.append(tmpStr + "\n");
            }
        } finally {
            inputStream.close();
        }
        ServiceDeployParam deployParam = JSON.parseObject(stringBuffer.toString(), ServiceDeployParam.class);
        return deployParam;
    }

    /**
     * 获取某个服务的部署默认值： 通用默认值 + 自己服务的默认值
     * <p>
     * 主要是从cicd_yml中获取healthCheckPath的值
     *
     * @param projectName yml中有projectName，我们要根据这个name来确定默认值。
     * @return
     */
    public static ServiceDeployParam getDefaultDeploymentForOneProject(String projectName, String env) {
        ServiceDeployParam serviceDeployParam = null;
        try {
            serviceDeployParam = getDeploymentParamDefaultCommonValue(env);
        } catch (IOException e) {
            e.printStackTrace();
        }
        serviceDeployParam.getHealthcheck().setPath(getHealthCheckPath(projectName, env));
        return serviceDeployParam;
    }

    /**
     * 获取某个项目的健康检测路径。
     *
     * @param projectName
     * @return
     */
    public static String getHealthCheckPath(String projectName, String env) {
        CicdInfoRoot cicdInfoRoot = getCicdInfoRoot(env);
        CicdInfo cicdInfo = cicdInfoRoot.getCicd();
        String healthCheckPath = cicdInfo.getCommon().getHealthCheckPath();
        for (ServerInfo serverInfo : cicdInfo.getServers()) {
            // 先找到服务的配置
            if (projectName.equals(serverInfo.getName())) {
                // 并且，服务有配置healthCheckPath这个属性
                if (StringUtils.isNotBlank(serverInfo.getHealthCheckPath())) {
                    healthCheckPath = serverInfo.getHealthCheckPath();
                }
            }
        }
        return healthCheckPath;
    }

    /**
     * 从配置文件中获取ServerInfo的信息
     *
     * @return
     */
    public static Map<String, ServerInfo> getServerInfoMap(String env) {
        CicdInfoRoot cicdInfoRoot = getCicdInfoRoot(env);
        CicdInfo cicdInfo = cicdInfoRoot.getCicd();
        List<ServerInfo> serverInfoList = cicdInfo.getServers();
        Map<String, ServerInfo> result = new HashMap<>();
        for (ServerInfo serverInfo : serverInfoList) {
            ServerInfo tmp = result.get(serverInfo.getName());
            if (tmp != null) {
                log.info("duplicateProjectName:{}", serverInfo.getName());
                continue;
            }
            result.put(serverInfo.getName(), serverInfo);
        }
        return result;
    }

    /**
     * 获取通用配置
     *
     * @return
     */
    public static CommonInfo getCommonInfo(String env) {
        CicdInfoRoot cicdInfoRoot = getCicdInfoRoot(env);
        CicdInfo cicdInfo = cicdInfoRoot.getCicd();
        return cicdInfo.getCommon();
    }


}

